package com.it.chinasoft.service.activiti;

import com.alibaba.fastjson.JSON;
import com.it.chinasoft.pojo.CustomerTask;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TransferWorkFlow {
    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
    private final static Logger logger = LoggerFactory.getLogger(ApplicationFlow.class);

    /**
     * 部署流程定义
     */
    @Test
    public void deployFlow() throws FileNotFoundException, FileNotFoundException {
        RepositoryService repositoryService = processEngine.getRepositoryService();

        FileInputStream bpmnStream = new FileInputStream("D:\\Programming\\Projects\\prusa\\src\\main\\resources\\processes\\transfer.xml");
        //得到流程引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        processEngine.getRepositoryService()
                .createDeployment()
                .name("顾客发起转账")
                .addInputStream("transferbpmn", bpmnStream)
                .deploy();
        //注意：inputStream不能带后缀，FileInputStream用全称。
        logger.info("部署转账工作流成功！");
    }

    /**
     * 启动刚刚部署的流程。
     */
    @Test
    public void StartProcessInstance(){
        logger.info("启动转账工作流，可以多次启动已经部署完成的工作流。");
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        String processInstanceKey = "transfer";
        String variableName = "汇总金额";
        // 启动流程实例
        ProcessInstance processInstance = processEngine.getRuntimeService()
                .startProcessInstanceByKey(processInstanceKey);
        // 查询执行对象
        /*Execution execution = processEngine.getRuntimeService().createExecutionQuery().processInstanceId(processInstance.getId()) // 流程实例ID
                .activityId("transfer:1:85004").singleResult(); */// 活动ID
    }

    /**
     * 查询待办任务列表
     */

    public List<CustomerTask> todoQueryTask(String assignee) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> taskList  = taskService.createTaskQuery().taskAssignee(assignee).list();
        List<CustomerTask> customerCurrentTasks = new ArrayList<>();
        for (Task task : taskList) {
            CustomerTask customerCurrentTask = new CustomerTask();
            customerCurrentTask.setTaskId(task.getId());
            customerCurrentTask.setAssignee(task.getName());
            customerCurrentTask.setProcessInstanceId(task.getProcessDefinitionId());
            customerCurrentTasks.add(customerCurrentTask);
        }
        logger.info(JSON.toJSONString(customerCurrentTasks));
        return customerCurrentTasks;
    }

    @Test
    public void commonTest(){
        List<CustomerTask> customerCurrentTasks = todoQueryTask("Tom");
        logger.info(JSON.toJSONString(customerCurrentTasks));
    }
    /**
     * @Title: findMyTaskListByUserId
     * @Description: TODO(根据用户Id查找所有的代办任务)
     * @param
     * @return List<Task> (这里用一句话描述返回结果说明)
     */
    public List<Task> findMyTaskListByUserId(String userId){
        List<Task> assigneeList = processEngine.getTaskService()
                .createTaskQuery()//指定个人任务查询
                .taskAssignee(userId)
                .list();

        List<Task> candidateUserList = processEngine.getTaskService()
                .createTaskQuery()//指定个人任务查询
                .taskCandidateUser(userId)
                .list();

        List<Task> listAll = new ArrayList<Task>();
        listAll.addAll(assigneeList);
        listAll.addAll(candidateUserList);

        List<Task> returnList = new ArrayList<Task>();
        Set<String> taskIdsSet = new HashSet<String>();
        for (int i = 0; i < listAll.size(); i++) {
            if (taskIdsSet.add(listAll.get(i).getId())) {
                returnList.add(listAll.get(i));
            }
        }
        return returnList;
    }




}
